﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using TeenyGrab.Classes;
using TeenyGrab.Helpers;

namespace TeenyGrab.UserControls
{
    /// <summary>
    /// Interaction logic for HotKeyUserControl.xaml
    /// </summary>
    public partial class HotkeyUserControl : System.Windows.Controls.UserControl
    {
        private Hotkey hotkey;
        public Hotkey Hotkey
        {
            get
            {
                return hotkey;
            }
            set
            {
                hotkey = value;
                UpdateDisplay();
            }
        }

        private List<Key> Pressed { get; set; }
        
        public HotkeyUserControl()
        {
            InitializeComponent();
            Hotkey = new Hotkey();
            Pressed = new List<Key>();
        }

        private void UpdateDisplay()
        {
            textBox.Text =
                (Hotkey.Ctrl ? "CTRL + " : "") +
                (Hotkey.Alt ? "ALT + " : "") +
                (Hotkey.Shift ? "SHIFT + " : "") +
                (Hotkey.Button != null ? Hotkey.Button.ToString() : "");
        }

        private List<Key> Modifiers = new List<Key>() { Key.LeftCtrl, Key.RightCtrl, Key.LeftAlt, Key.RightAlt, Key.LeftShift, Key.RightShift };
        private void textBox_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if(Modifiers.Contains(e.Key))
            {
                if (Pressed.Contains(e.Key))
                {
                    Pressed.Remove(e.Key);
                }
            }
            else
            {
                Hotkey.Shift = Pressed.Contains(Key.LeftShift) || Pressed.Contains(Key.RightShift);
                Hotkey.Ctrl = Pressed.Contains(Key.LeftCtrl) || Pressed.Contains(Key.RightCtrl);
                Hotkey.Alt = Pressed.Contains(Key.LeftAlt) || Pressed.Contains(Key.RightAlt);
                Hotkey.Button = e.Key.WPFToWinformsKey();
                UpdateDisplay();
            }
            e.Handled = true;
        }

        private void textBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (Modifiers.Contains(e.Key))
            {
                if (!Pressed.Contains(e.Key))
                {
                    Pressed.Add(e.Key);
                }
            }
            e.Handled = true;
        }
    }
}
